﻿using Shop.Model.DB;
using Shop.RemoteModel.CouponGoods.Model;
using WeDonekRpc.Helper;
using WeDonekRpc.Helper.IdGenerator;
using WeDonekRpc.SqlSugar;

namespace Shop.Repository.lmpl
{
    internal class CouponGoodsRepository : ShopBaseRepository<DBShopCouponGoods, long>, ICouponGoodsRepository
    {
        public CouponGoodsRepository (ISqlClientFactory factory) : base(factory)
        {
        }

        public void Sync (DBShopCouponGoods[] adds, long[] dropId, long activityId, int num)
        {
            ISqlQueue<DBShopCouponGoods> queue = base.BeginQueue();
            queue.UpdateOneColumn<DBShopCoupon>(c => c.SkuNum == num, c => c.Id == activityId);
            if (!adds.IsNull())
            {
                queue.Insert(adds);
            }
            if (!dropId.IsNull())
            {
                queue.Delete(a => dropId.Contains(a.Id));
            }
            _ = queue.Submit();
        }
        public long[] GetSkuIds (long couponId)
        {
            return base.Gets(a => a.CouponId == couponId, a => a.SkuId);
        }
        public Result[] GetsByCouponId<Result> (long couponId) where Result : class, new()
        {
            return base.Gets<Result>(a => a.CouponId == couponId);
        }

        public DBShopCouponGoods[] Adds (long couponId, CoupGoods[] goods)
        {
            DBShopCouponGoods[] adds = goods.ConvertAll(c => new DBShopCouponGoods
            {
                CouponId = couponId,
                GoodsId = c.GoodsId,
                SkuId = c.SkuId,
                Id = IdentityHelper.CreateId()
            });
            long len = goods.Length;
            ISqlQueue<DBShopCouponGoods> queue = base.BeginQueue();
            queue.UpdateOneColumn<DBShopCoupon>(c => c.SkuNum == len, c => c.Id == couponId);
            queue.Insert(adds);
            queue.Submit();
            return adds;
        }
    }
}
